package com.boxin.ims.modules.wechat.utils;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.boxin.ims.modules.wechat.busi.BusinessProcessor;
import com.boxin.ims.modules.wechat.entity.BusinessConfig;
import com.boxin.ims.modules.wechat.entity.TextMessage;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatBusiness;
import com.boxin.ims.modules.wechat.entity.WechatConfig;
import com.boxin.ims.modules.wechat.entity.share.RuleType;
import com.boxin.ims.modules.wechat.service.BusinessConfigService;
import com.boxin.ims.modules.wechat.service.WechatBusinessService;
import com.boxin.ims.modules.wechat.service.WechatConfigService;
import com.google.common.collect.Maps;

/**
 * @author Jakemanse
 * @date 2013-10-24
 * @function <p>用户消息处理分发器 </p>
 */
@Service
public class MessageProcessorUtils  implements ApplicationContextAware{

	private static final String BUSINESS_CONFIG_KEY = "BUSINESS_CONFIG_KEY_";
	private static final String BUSINESS_USER_KEY = "BUSINESS_USER_KEY_";
	private static BusinessConfigService businessConfigService;
	private static List<BusinessConfig> businessConfigs;
	private static WechatBusinessService wechatBusinessService;
	private static WechatConfigService wechatConfigService;
	private static Map<String, Object> cacheMap;
	
	
	
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		businessConfigService =  (BusinessConfigService)applicationContext.getBean("businessConfigService");
		wechatBusinessService =  (WechatBusinessService)applicationContext.getBean("wechatBusinessService");
		wechatConfigService =  (WechatConfigService)applicationContext.getBean("wechatConfigService");
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-24  下午2:45:46
	 * @function <p>  </p>
	 * @param userId
	 * @return
	 */
	public static  List<BusinessConfig> getBusinessConfigs(Long userId){
		WechatBusiness wechatBusiness = 	wechatBusinessService.getByUserId(userId);
		
		if(wechatBusiness != null){
			businessConfigs = wechatBusiness.getBusinessConfigList();
		}
		return businessConfigs;
	}
	
	
	

	/**
	 * @author Jakemanse
	 * @time 2013-10-23  下午3:45:59
	 * @function <p>查 配置服务  </p>
	 * @param id
	 * @return
	 */
	public static BusinessConfig getBusinessConfigById(Long id){
		BusinessConfig config = (BusinessConfig)getCache(BUSINESS_CONFIG_KEY + id);
		if(config == null){
			config = businessConfigService.get(id);
			putCache(BUSINESS_CONFIG_KEY + id, config);
		}
		
		return config;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-23  下午3:49:54
	 * @function <p> 查询用户的配置服务列表 </p>
	 * @param userId
	 * @return
	 */
	public static List<BusinessConfig> getBusinessConfigListByUserId(Long userId){
		
		WechatBusiness business = (WechatBusiness)getCache(BUSINESS_USER_KEY+userId);
		if(business == null){
			business = wechatBusinessService.getByUserId(userId);
			if(business!=null)
				putCache(BUSINESS_USER_KEY+userId, business);
		}		
		
		return (business==null)?null : business.getBusinessConfigList();
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-23  下午3:54:54
	 * @function <p> 获取消息处理器 </p>
	 * @param keyword
	 * @return
	 */
	public static BusinessProcessor getBusinessProcessorByKeywords(WeChat weChat,TextMessage processorMessage,Map<String,String> map,HttpServletRequest request, HttpServletResponse response){
		String keyword = processorMessage.getContent();
		String openId = processorMessage.getToUserName();	//Open Id
		//WechatConfig wechatConfig = wechatConfigService.getByUpcontentAndWechatId(weChat.getId(),keyword);
		BusinessProcessor businessProcessor = (BusinessProcessor)SpringUtils.getBean("defaultProcessor");
		
		//if(wechatConfig != null && wechatConfig.getBusinessConfig()!=null){
//			BusinessConfig config = wechatConfig.getBusinessConfig();
			BusinessConfig config = getBusinessByKeywords(weChat.getUser().getId(), keyword);
			if(config != null){
				businessProcessor = (BusinessProcessor)SpringUtils.getBean(config.getBeanId());
				businessProcessor.setUrl(config.getUrl());
				businessProcessor.setNeedMember(config.isNeedBeMember());
			}
			if(businessProcessor == null || config==null){
				businessProcessor = (BusinessProcessor)SpringUtils.getBean("defaultProcessor");
			}
		//}
		
		businessProcessor.setUser(weChat.getUser());
		businessProcessor.setWeChat(weChat);
		businessProcessor.setOpenId(openId);
		businessProcessor.setRequest(request);
		businessProcessor.setResponse(response);
		businessProcessor.setMessageMap(map);
		businessProcessor.setTextMessage(processorMessage);
		
		return businessProcessor;
		
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-9-11  上午11:18:51
	 * @function <p>根据Bean Id 查找 Spring 容器中的Bean  </p>
	 * @param beanId
	 * @return
	 */
	public static BusinessProcessor  getByBeanId(String beanId){
		return (BusinessProcessor)SpringUtils.getBean(beanId);
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-23  下午3:39:21
	 * @function <p> 根据关键词查询对应的消息服务处理器 </p>
	 * @param keyword
	 * @return
	 */
	public static BusinessConfig  getBusinessByKeywords(Long userId,String keyword){
		List<BusinessConfig>  configs = getBusinessConfigListByUserId(userId);
		
		if(configs!=null && !configs.isEmpty()){
			for(BusinessConfig config : configs){
				switch(config.getRuleType()){
				case 1:
					if(config.getKeywords().equals(keyword)){
						return config;
					}
					break;
				case 2:
					if(config.getKeywords().contains(keyword)){
						return config;
					}
					break;
				case 6:
					if(keyword.startsWith(config.getKeywords())){
						return config;
					}
					break;
				case 7:
					if(keyword.endsWith(config.getKeywords())){
						return config;
					}
					break;
				}
			}
			
		}
		return null;
	}
	
	
	
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getCacheMap().get(key);
		return obj==defaultValue?defaultValue:obj;
	}
	
	public static void putCache(String key, Object value) {
		getCacheMap().put(key, value);
	}
	
	public static void removeCache(String key) {
		getCacheMap().remove(key);
	}
	
	private static Map<String, Object> getCacheMap(){
		Map<String, Object> map = Maps.newHashMap();
		try{
			return cacheMap!=null?cacheMap:map;
		}catch (Exception e) {
			return cacheMap;
		}
	}

}
